#服务数据服务顾问统计(业绩,排行)服务类  flydragon
class StatisticalDatum::ServiceAdvisorService
  include HeiPisService

  #company 单位
  #studio 分店
  def initialize(company, studio)
    @company = company
    @studio = studio
  end


  #执行方法 返回值
  def call

    #======服务顾问业绩前十名=======#

    sale_order_info = sale_order
    comment_order_info = comment_order

    Result.new(sale_order_info[:names],sale_order_info[:values],comment_order[:names],comment_order[:values])
  end


  #销售排行
  def sale_order

    filter_params = {:company_id => @company.id }
    filter_params[:start_date] = Date.current - 30.day
    filter_params[:end_date] = Date.current

    sql_where = " where stu.company_id = :company_id and (ord.created_at between :start_date and :end_date) "
    if @studio.present?
      filter_params[:studio_id] = @studio.id 
      sql_where += " and ord.studio_id = :studio_id"
    end
    sql = %Q{
      select sum(total_price) as sale_amount,em.name 
      from orders ord join students stu on ord.student_id = stu.id 
      join employees em on stu.service_employee_id = em.id 
      #{sql_where}
      group by stu.service_employee_id order by sale_amount asc limit 10;
    }

    sale_names = Array.new(10,'未知')
    sale_values = Array.new(10, 0 )

    Order.find_by_sql([sql,filter_params]).each do |record|
      sale_names << record.name
      sale_values << record.sale_amount
    end
    
    {:names => sale_names[-10,10],:values => sale_values[-10,10]}
  end


  #评论排行
  def comment_order

    filter_params = {:company_id => @company.id }
    filter_params[:start_date] = Date.current - 30.day
    filter_params[:end_date] = Time.now

    sql_where = " where em.company_id = :company_id and (stu_r.created_at between :start_date and :end_date) "
    if @studio.present?
      filter_params[:studio_id] = @studio.id 
      sql_where += " and stu.studio_id = :studio_id"
    end
    sql = %Q{
      select count(stu_r.service_employee_id) as remark_count,em.name 
      from student_remarks stu_r
      join employees em on stu_r.service_employee_id = em.id
      join students stu on stu.id = stu_r.student_id 
      #{sql_where}
      group by stu_r.service_employee_id order by remark_count asc limit 10;
    }

    sale_names = Array.new(10,'未知')
    sale_values = Array.new(10, 0 )

    Order.find_by_sql([sql,filter_params]).each do |record|
      sale_names << record.name
      sale_values << record.remark_count
    end
    
    {:names => sale_names[-10,10],:values => sale_values[-10,10]}
  end


  #内部类,指定结果返回值
  class Result
  	attr_reader :sale_names, :sale_values,:comment_names,:comment_values

    #sale_names 销售排行名列表
    #sale_values 销售业绩排行列表
    #comment_names 评论排行列表
    #comment_values 评论排行列表
	  def initialize(sale_names, sale_values ,comment_names,comment_values)
      @sale_names = sale_names
      @sale_values = sale_values
      @comment_names = comment_names
      @comment_values = comment_values
    end 

  end

end
